﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleMaintenance.Models;
using VehicleMaintenance.Framework;

namespace VehicleMaintenance.Transaction
{
    public partial class WorkForm : BaseForm
    {
        public WorkForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 打开修理或结算窗口
        /// </summary>
        /// <param name="state">当前修理状态</param>
        public WorkForm(string state)
        {
            InitializeComponent();

            BindMainBill(state);
        }

        private void WorkForm_Load(object sender, EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void cboxState_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cboxState.SelectedIndex > -1)
                {
                    BindMainBill(cboxState.Text);

                    switch (cboxState.Text)
                    {
                        case "已登记":
                            {
                                btnSettle.Visible = false;
                                btnAddBill.Visible = true;
                                btnEdit.Visible = true;
                                btnDel.Visible = true;
                                btnDelMainBill.Visible = true;
                                //lvBill.CheckBoxes = false;
                                break;
                            }
                        case "修理中":
                            {
                                btnSettle.Visible = true;
                                btnAddBill.Visible = true;
                                btnEdit.Visible = true;
                                btnDel.Visible = true;
                                btnDelMainBill.Visible = true;
                                //lvBill.CheckBoxes = false;
                                btnSettle.Text = "修理完成"; break;
                            }
                        case "已完成":
                            {
                                btnSettle.Visible = true;
                                btnAddBill.Visible = false;
                                btnEdit.Visible = false;
                                btnDel.Visible = false;
                                btnDelMainBill.Visible = false;
                                //lvBill.CheckBoxes = true;
                                btnSettle.Text = "结算"; break;
                            }
                    }
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                MainBillForm form = new MainBillForm();
                form.ShowInTaskbar = false;
                form.ShowDialog(this);

                BindMainBill("已登记");
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void btnAddBill_Click(object sender, EventArgs e)
        {
            try
            {
                if (lvMainBill.SelectedItems.Count > 0)
                {
                    string mainCode = lvMainBill.SelectedItems[0].Tag.ToString();
                    RecipientsBillForm form = new RecipientsBillForm(mainCode);
                    form.ShowInTaskbar = false;
                    form.ShowDialog(this);
                    //lvMainBill_SelectedIndexChanged(sender, e);
                    //一旦添加领用，即认为开始修理中
                    string str = "修理中";
                    CarDBContext db = new CarDBContext();
                    MainBill mainBill = db.MainBill.First(p => p.MainBillCode == mainCode);
                    mainBill.State = str;
                    mainBill.BeginDate = DateTime.Now.ToString("yyyy年MM月dd日");
                    db.SaveChanges();

                    //if (cboxState.Text != str)
                    {
                        BindMainBill(str);
                        if (lvMainBill.Items.Count > 0)
                        {
                            //lvMainBill.Items[lvMainBill.Items.Count - 1].Selected = true;
                            ListViewItem lv = lvMainBill.Items.Find(mainCode, true)[0];
                            lv.Selected = true;
                            lv.Checked = true;
                        }
                    }
                }
                else
                {
                    this.ShowInfo("请先在左侧选择主单");
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (lvBill.SelectedItems.Count > 0)
                {
                    int id = Convert.ToInt32(lvBill.SelectedItems[0].Tag);
                    RecipientsBillForm form = new RecipientsBillForm(id);
                    form.ShowInTaskbar = false;
                    if (form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                    {
                        lvMainBill_SelectedIndexChanged(sender, e);
                    }
                }
                else
                {
                    this.ShowInfo("请选择要编辑的领用单");
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (lvBill.SelectedItems.Count > 0)
                {
                    if (MessageBox.Show(this, "确认删除选中领用单吗？", "提示", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
                    {
                        return;
                    }
                    int id = Convert.ToInt32(lvBill.SelectedItems[0].Tag);
                    CarDBContext db = new CarDBContext();
                    RecipientsBill bill = db.RecipientsBill.Include("Good").First(p => p.ID == id);
                    int goodID = bill.Good.GoodID;
                    db.RecipientsBill.Remove(bill);
                    //更新库存
                    db.Goods.Find(goodID).Number += bill.Number;
                    db.SaveChanges();

                    lvBill.Items.RemoveAt(lvBill.SelectedItems[0].Index);
                    this.ShowInfo("删除领用单成功");
                }
                else
                {
                    this.ShowInfo("请选择要删除的领用单");
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void BindMainBill(string state)
        {
            try
            {
                this.cboxState.Text = state;
                lvMainBill.Items.Clear();
                CarDBContext db = new CarDBContext();
                var mainBills = db.MainBill.Include("Car").Where(p => p.State == state && p.IsSettle == 0).OrderBy(p => p.ID);
                foreach (var item in mainBills)
                {
                    ListViewItem lv = new ListViewItem(new string[] { item.MainBillCode, item.CarNO, item.Car.CarName });
                    lv.Tag = item.MainBillCode;
                    lv.Name = item.MainBillCode;
                    lvMainBill.Items.Add(lv);
                }

                lvBill.Items.Clear();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void lvMainBill_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lvMainBill.SelectedItems.Count > 0)
                {
                    lvBill.Items.Clear();
                    CarDBContext db = new CarDBContext();
                    string mainBillCode = lvMainBill.SelectedItems[0].Tag.ToString();
                    var bills = db.RecipientsBill.Include("Good").Include("CarType").Include("Staff").Where(p => p.MainBillCode == mainBillCode).OrderBy(p => p.ID);
                    foreach (var item in bills)
                    {
                        ListViewItem lv = new ListViewItem(new string[] { item.Code,item.Position,item.Date,item.Good.Code,item.Good.Name,
                                                            item.CarType.Name,item.Number.ToString(),item.UnitPrice.ToString(),item.TotalPrice.ToString(),
                                                            item.OfferAmount.ToString(),item.SalesAmount.ToString(),item.Payment,item.Staff != null ? item.Staff.Name : ""});
                        lv.Tag = item.ID;
                        lvBill.Items.Add(lv);
                        //if (item.IsSettle == 1)
                        //{
                        //    lv.Checked = false;
                        //    lv.BackColor = Color.Gray;
                        //}
                        //else
                        //{
                        //    lv.Checked = true;
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void btnSettle_Click(object sender, EventArgs e)
        {
            try
            {
                if (lvMainBill.SelectedItems.Count > 0)
                {
                    if (lvBill.Items.Count > 0)
                    {
                        string mainBillCode = lvMainBill.SelectedItems[0].Tag.ToString();
                        switch (cboxState.Text)
                        {
                            case "已登记":
                                {
                                    break;
                                }
                            case "修理中":
                                {
                                    if (MessageBox.Show(this, "确认修理完成吗？", "提示", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                                    {
                                        CarDBContext db = new CarDBContext();
                                        MainBill bill = db.MainBill.First(p => p.MainBillCode == mainBillCode);
                                        bill.State = "已完成";
                                        bill.FinishDate = DateTime.Now.ToString("yyyy年MM月dd日");
                                        db.SaveChanges();
                                        BindMainBill(cboxState.Text);
                                    }
                                    break;
                                }
                            case "已完成":
                                {
                                    //CarDBContext db = new CarDBContext();
                                    //List<RecipientsBill> list = new List<RecipientsBill>();
                                    //foreach (ListViewItem item in lvBill.Items)
                                    //{
                                    //    if (item.Checked)
                                    //    {
                                    //        int id = Convert.ToInt32(item.Tag);
                                    //        RecipientsBill bill = db.RecipientsBill.Include("Good").First(p => p.ID == id);
                                    //        list.Add(bill);
                                    //    }
                                    //}
                                    SettleForm form = new SettleForm(mainBillCode);
                                    form.ShowInTaskbar = false;
                                    if (form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                                    {
                                        BindMainBill(cboxState.Text);
                                    }
                                    break;
                                }
                        }
                    }
                    else
                    {
                        this.ShowInfo("当前单号未添加任何领用，请核实！");
                    }
                }
                else
                {
                    this.ShowInfo("请选择要结算的主单");
                    lvMainBill.Focus();
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void lvBill_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            //if (e.CurrentValue == CheckState.Checked)
            //{
            //    if (lvBill.Items[e.Index].BackColor == Color.Gray)
            //    {
            //        e.NewValue = CheckState.Unchecked;
            //    }
            //}
        }

        private void btnDelMainBill_Click(object sender, EventArgs e)
        {
            try
            {
                if (lvMainBill.SelectedItems.Count > 0)
                {
                    if (MessageBox.Show(this, "确认删除选中的主单吗？\r\n同时会删除相关零用单", "提示", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
                    {
                        return;
                    }
                    string mainBillCode = lvMainBill.SelectedItems[0].Tag.ToString();
                    CarDBContext db = new CarDBContext();//db.Database.ExecuteSqlCommand
                    var bills = db.RecipientsBill.Where(p => p.MainBillCode == mainBillCode).ToList();
                    if (bills != null)
                    {
                        foreach (var item in bills)
                        {
                            int num = item.Number;
                            db.RecipientsBill.Remove(item);
                            //更新库存
                            Goods good = db.Goods.Find(item.GoodID);
                            good.Number += num;
                        }
                    }

                    db.MainBill.Remove(db.MainBill.First(p => p.MainBillCode == mainBillCode));
                    lvBill.Items.Clear();

                    db.SaveChanges();

                    lvMainBill.Items.RemoveAt(lvMainBill.SelectedItems[0].Index);
                    this.ShowInfo("删除领用单成功");
                }
                else
                {
                    this.ShowInfo("请选择要删除的主单");
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }
    }
}
